package cn.shengchao.controler.ycbdc;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.shengchao.examstar.product.ohs.local.appservice.ProductAppService;
import cn.shengchao.examstar.product.ohs.local.message.ProductDto;
import cn.shengchao.examstart.user.acl.adapters.repositories.UserRepository;
import cn.shengchao.examstart.user.domain.entity.User;
import cn.shengchao.util.helper.LoginHelper;
import cn.shengchao.ycbdc.acl.ports.repositories.IProductThirdYcbdcUserOrderRepository;
import cn.shengchao.ycbdc.domain.token.YcBdcTokenUtil;
import cn.shengchao.ycbdc.infrastructure.dao.po.ProductThirdYcbdcUserOrder;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.continew.starter.web.model.R;

import java.util.Date;
import java.util.List;

/**
 * @program: examstarapi
 * @description: 忆成背单词第三方对接
 * @author: Xiong weiqiang
 * @create: 2025-06-04 10:50
 */
@Slf4j
@RestController
@CrossOrigin("${project.cross-origin}")
@RequestMapping("/api/${project.version}/productThirdYcbdc")
public class YcBdcController {
    @Autowired
    private YcBdcTokenUtil ycBdcTokenUtil;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private ProductAppService productAppService;
    @Autowired
    IProductThirdYcbdcUserOrderRepository productThirdYcbdcUserOrderRepository;
    @GetMapping("token")
    public R<String> getToken() {
        Long userId= LoginHelper.getUserId();
        User user =userRepository.of(userId);
        String phone=productThirdYcbdcUserOrderRepository.getPhoneForUserId(userId);
        System.out.printf("=============================获取忆成英语token,userId: %s 手机号：%s%n",userId,phone);
        if (StrUtil.isNotBlank( phone)){
            String tokenResp= ycBdcTokenUtil.getRedisToken(phone,user.getName());
            return R.ok(tokenResp);
        }else {
            return R.fail(R.fail().getCode(), "用户手机号错误");
        }
    }
    @SaIgnore
    @GetMapping("productInfo/{productYcId}")
    @Operation(summary = "获取忆成第三方服务产品", description = "获取忆成第三方服务产品")
    public ProductDto getProductThirdYcbdc(@PathVariable Long productYcId) {
        return productAppService.getProductById(String.valueOf(productYcId));
    }

    @GetMapping("userDate/{mobile}")
    public R<Date> getToken(@PathVariable String mobile) {
        List<ProductThirdYcbdcUserOrder> list= productThirdYcbdcUserOrderRepository.queryByWrapper(Wrappers.lambdaQuery(ProductThirdYcbdcUserOrder.class)
                .eq(ProductThirdYcbdcUserOrder::getMobile,mobile)
                .eq(ProductThirdYcbdcUserOrder::getDataStatus,1)
        );
        return R.ok(CollUtil.isEmpty(list)?null:list.get(0).getExpirationDate());
    }
}